#function(td, input, param2)
/* 默认值 */
local input_default = table{
	// 工程信息
	info : table {
		// 输入文件信息
		folder : "";
		name   : "example.json"
	};


	// 频率设置
    freq : table {
        min : 10;
        max : 30;
        nsp : 1001
    };

	// 激励设置
    source : table {
		type  : "theta-phi"; // theta-phi / XYZ
        theta : 90;
        phi   : 0;
        alpha : 0
    };

	// 信号设置
    signal : table {
		type : "doubleexp";  // doubleexp / import
        A : 50;
        k : 1.05;
        alpha : 4e6;
        beta : 4.76e8
    };

	// 单位设置
    unit : table {
        ul : "1e-3";
        uf : "1e6";
        ut : "1e-6"
    };

	// 最大仿真时间
    time : table {
        max : "10"
    };

	// 模型例子
    model : [
        table {
            name : "A380";
            file : "app:/scripting/solver/EMP/A380.stl";
            material : "pec"
        }
    ];

	// 材料库例子
    material : [
        table {
            name : "pec";
            type : "pec"
        },

        table {
            name : "pvc";
            type : "simple";
            epsilon : "2.8";
            sigma_e : "0";
            mu      : "1.0";
            sigma_m : "0"
        },

        table {
            name : "rubber";
            type : "simple";
            epsilon : "3.5";
            sigma_e : "0";
            mu      : "1.0";
            sigma_m : "0"
        },

        table {
            name : "copper";
            type : "simple";
            epsilon : "1.0";
            sigma_e : "5.8e7";
            mu      : "1.0";
            sigma_m : "0"
        }, 

		table {
			name : "lossy_material";
			type : "lossy";
			epsilon : "3.0";
			tan_e   : "0.001";
			mu      : "1.0";
			tan_m   : "0";
			freq    : "freq.val"
		}

    ];

	//场点、区域、体监视器例子
    probe : [
        table {
            name : "probe_1";
			type : "file";
            file : "app:/scripting/solver/EMP/probe_1.txt";
        },
        table {
            name : "probe_2";
			type : "file";
            file : "app:/scripting/solver/EMP/probe_2.txt";
        },
		table {
			name : "probe_3";
			type : "data";
			data : [0,0,0,
					100,0,0]
		}
    ];

	// 线缆例子
	cable : [
		table {
			file  : "app:/scripting/solver/EMP/input_cable.txt";
			name  : "cable-1";
			type  : "DCableWireSingleWithBase"
		}
	];

	// 表面监视器例子
	surface : [
		table {
			model  : "app:/scripting/solver/EMP/A380.stl";
			name   : "surface_monitor";
			type   : "DMonitorSurface";
			freq   : [0.3, 0.6]
		}
	]

};


// 处理默认值
local union_default = function(tb, tb_default)
{
    if(is_nil(tb)) return tb_default;

    for(k, v in tb_default)
    {
        if(is_table(v))
        {
			if(is_nil(tb[k]))
			{
				tb[k] = v;
			}
			else
			{
            	tb[k] = self(tb[k], tb_default[k]);
			}

        }else if(is_array(v))
		{
			if(is_nil(tb[k]))
			{
				tb[k] = [];
			}
		}
		else
        {
			// 用户输入没有定义，则使用默认值
            if(is_nil(tb[k]))
            {
                tb[k] = v;
            }
        }
    }

    return tb;
};

logger.log_message("** Before Union **");
table.view(input);
input = union_default(input, input_default);

// DEBUG代码：发布前要注释
// io.save_var("app:/scripting/solver/EMP/input.mxd", input);


logger.log_message("** After Union **");
table.view(input)

local freq = input.freq;
local source = input.source;
local signal = input.signal;
local unit = input.unit;
local time = input.time;

local model = input.model;
local material = input.material;
local surface = input.surface;

local input_file = fs.makepath(input.info.name, input.info.folder);
local output_file = input.output.file;


local param_file= fs.makepath("input_param.mxd",input.output.fpath);
/* DEBUG FILENAME */
/*

logger.log_message("input_file: %s", input_file);
logger.log_message("input_file_folder: %s", input.info.folder);
logger.log_message("output_file: %s", output_file);

return;

*/
/* END OF DEBUG */

// 载入线缆数据
local cable = input.cable;
// println("Cable File:" .. cable[0].file)
// local cable_data = io.readfile(cable[0].file);

// 构造工程
// global td;

td.beg("doc","DDocument");

	td.set("s_template","default");
	td.set("flags#ddoc",0x0);
	td.set("version#ddoc",0x134FDF7);


    // 设置变量表
	td.beg("vartable","DVariable");
		td.set("variables",
            [
				// 仿真信息
                ["freq_min";freq.min;""];
                ["freq_max";freq.max;""];
                ["freq_nsp";freq.nsp;""];
                ["time_max";time.max;""];
                ["plw_theta";source.theta;""];
                ["plw_phi";source.phi;""];
                ["plw_alpha";source.alpha;""];
                ["signal_A";signal.A;""];
                ["signal_k";signal.k;""];
                ["signal_alpha";signal.alpha;""];
                ["signal_beta";signal.beta;""];

				// 额外信息
				["input_file";"'" .. input_file .. "'";""];
				["output_file";"'" .. output_file .. "'";""];
				["param_file";"'" .. param_file .. "'";""]
            ]
        );
		td.set("type#DVariable",0x0);
		td.set("script#var#DVariable","");
	td.end();

	// 顶层组
	td.beg("topgroup1","DSymbolGrp");
		td.set("unit","");
		td.set("meshinfo","");
		td.set("material","");
		td.set("n_dp_level",0x0);
		td.set("flg_style#decorator",0x0);
		td.set("exp_extra#decorator","");
		td.set("opt_extra_mode#decorator",0x0);
		td.set("sym_extra_function#decorator","");
		td.set("sym_extra_npDistrib#decorator","");
		td.set("flg_npDistrib_show#decorator",0x0);
		td.set("transforms",[]);
		td.set("children",["source"]);     //
		td.set("reference","source");
	td.end();

	// 求解器参数
	td.beg("config","DParameterTD");
		td.set("unit","unit");
		td.set("bgmat","#ddoc.material.vacuum");
		td.set("fbox.lo.x","-300");
		td.set("fbox.lo.y","-300");
		td.set("fbox.lo.z","-300");
		td.set("fbox.hi.x","300");
		td.set("fbox.hi.y","300");
		td.set("fbox.hi.z","300");
		td.set("fbox.policy",0x1);
		td.set("border.lo.x",0x0);
		td.set("border.lo.y",0x0);
		td.set("border.lo.z",0x0);
		td.set("border.hi.x",0x0);
		td.set("border.hi.y",0x0);
		td.set("border.hi.z",0x0);
		td.set("symmetry.x#DParameterTD",0x0);
		td.set("symmetry.y#DParameterTD",0x0);
		td.set("symmetry.z#DParameterTD",0x0);
		td.set("time.step_max","1000");
		td.set("time.time_max", "time_max");
		td.set("time.dt_ratio","0.9");
		td.set("time.dt_reference","1.0");
		td.set("time.policy",0x0);
		td.set("time.time_max_policy",0x0);
		td.set("time.time_cycle","20.0");
		td.set("time.scale_factor","4.0");
		td.set("pml.size","12");
		td.set("pml.type",0x0);
		td.set("pml.sigma","8.0");
		td.set("pml.alpha","0.0");
		td.set("pml.kappa","1.0");
		td.set("bloch.k.x","0");
		td.set("bloch.k.y","0");
		td.set("bloch.k.z","0");
		td.set("addspace.type",0x0);
		td.set("addspace.val","0.25*lambda.val");
		td.set("addspace.box.lo.x","0.25*lambda.val");
		td.set("addspace.box.lo.y","0.25*lambda.val");
		td.set("addspace.box.lo.z","0.25*lambda.val");
		td.set("addspace.box.hi.x","0.25*lambda.val");
		td.set("addspace.box.hi.y","0.25*lambda.val");
		td.set("addspace.box.hi.z","0.25*lambda.val");
		td.set("freq.min","freq_min");
		td.set("freq.max","freq_max");
		td.set("freq.nsp","101");
		td.set("freq.num","11");
		td.set("output.folder","$(FULLPATH).data");
		td.set("output.name","$(FILENAME)");
		td.set("output.model_policy",0x0);
		td.set("solver.microengine.policy",0x0);
		td.set("solver.microengine.size","31");
		td.set("solver.auto_end_db","30");
		td.set("solver.step_min","1000");
		td.set("solver.flags",0x1);
		td.set("solver.fillmethod",0x0);
		td.set("viewer.type",0x0);
		td.set("viewer.flags",0x0);
		td.set("viewer.slice",0x2);
		td.set("viewer.field",0x2);
		td.set("viewer.position","0");
	td.end();

	// 网格设置
	td.beg("meshsetting","DMeshsetting");
		td.set("meshinfo.basic.flags",0x0);
		td.set("meshinfo.basic.delta.x","10.0");
		td.set("meshinfo.basic.delta.y","10.0");
		td.set("meshinfo.basic.delta.z","10.0");
		td.set("meshinfo.basic.extend.x","0.0");
		td.set("meshinfo.basic.extend.y","0.0");
		td.set("meshinfo.basic.extend.z","0.0");
		td.set("meshinfo.refine.flags",0x427);
		td.set("meshinfo.refine.edge_factor","1.0");
		td.set("meshinfo.refine.vol_factor","1.0");
		td.set("meshinfo.snapping.flags",0x30016);
		td.set("meshinfo.config.flags",0x0);
		td.set("meshinfo.config.edge_fraction","3.0");
		td.set("meshinfo.config.vol_smooth_ratio","1.1");
		td.set("meshinfo.config.edge_additional_fine_cells",0x3);
		td.set("meshinfo.config.min_vertical_face_area","0.0");
		td.set("meshinfo.config.vol_additional_fine_cells","3");
		td.set("meshinfo.config.num_near","15");
		td.set("meshinfo.config.num_far","15");
		td.set("meshinfo.config.max_delta_ratio","10");
		td.set("meshinfo.config.delta_max_near.x","lambda.ref/10.0");
		td.set("meshinfo.config.delta_max_near.y","lambda.ref/10.0");
		td.set("meshinfo.config.delta_max_near.z","lambda.ref/10.0");
		td.set("meshinfo.config.delta_max_far.x","lambda.ref/10.0");
		td.set("meshinfo.config.delta_max_far.y","lambda.ref/10.0");
		td.set("meshinfo.config.delta_max_far.z","lambda.ref/10.0");
		td.set("meshinfo.config.delta_min.x","lambda.val");
		td.set("meshinfo.config.delta_min.y","dy*0.95");
		td.set("meshinfo.config.delta_min.z","dz*0.95");
		td.set("meshinfo.conformal.level_e",0x3);
		td.set("meshinfo.conformal.level_h",0x3);
		td.set("meshinfo.conformal.line_policy",0x2);
		td.set("meshinfo.conformal.line_fc_policy",0x1);
		td.set("meshinfo.conformal.flags",0xD);
		td.set("meshinfo.conformal.sglrt_ratio_enable","0.2");
		td.set("meshinfo.conformal.SC_error","3.0");
		td.set("meshinfo.conformal.Area_thres_v1","0.0");
		td.set("meshinfo.conformal.Area_thres_v2","0.05");
		td.set("meshinfo.conformal.Line_thres_v1","0.0");
		td.set("meshinfo.conformal.Line_thres_v2","0.05");
		td.set("meshinfo.conformal.flags_discretization",0x3);
		td.set("meshinfo.conformal.delta_line_gap","1e-8");
		td.set("meshinfo.conformal.delta_line_pc","1e-8");
		td.set("meshinfo.conformal.delta_loop_pc","1e-8");
		td.set("meshinfo.conformal.flg_delta_type",0x1);
		td.set("meshinfo.mesh.type",0x1);
		td.set("meshinfo.mesh.grid.x","50");
		td.set("meshinfo.mesh.grid.y","50");
		td.set("meshinfo.mesh.grid.z","50");
		td.set("padjust.type",0x0);
		td.set("padjust.policy",0x0);
		td.set("padjust.eps_absolute","");
		td.set("padjust.eps_bylambda","0.0001");
	td.end();

	// 计算模式（暂时使用自定义模式）
	td.beg("EMP","DWorkmodeCustom");
		td.set("unit","");
	td.end();

    // 设置激励源
	td.beg("source","DSourceTFSF");
		td.set("unit","");
		td.set("flg_update_as_shape#Source",0x0);
		td.set("sym_signal#Source#TimeFunc","signal_default");
		td.set("exp_intensity#Source#TimeFunc","signal_A * signal_k");
		td.set("exp_delay#Source#TimeFunc","0.0");
		td.set("exp_phase#Source#TimeFunc","0.0");
		td.set("flg_autobox#Source#TFSF",0x1);
		td.set("exp_addspace#Source#TFSF","lambda.val * 0.5");
		td.set("x3e_box_lo.x#Source#TFSF","bbox.lo.x - lambda.val * 0.25");
		td.set("x3e_box_lo.y#Source#TFSF","bbox.lo.y - lambda.val * 0.25");
		td.set("x3e_box_lo.z#Source#TFSF","bbox.lo.z - lambda.val * 0.25");
		td.set("x3e_box_hi.x#Source#TFSF","bbox.hi.x + lambda.val * 0.25");
		td.set("x3e_box_hi.y#Source#TFSF","bbox.hi.y + lambda.val * 0.25");
		td.set("x3e_box_hi.z#Source#TFSF","bbox.hi.z + lambda.val * 0.25");
		td.set("sym_background_mat#Source#TFSF","#ddoc.material.vacuum");
		td.set("flg_enable_numdisp_modification#Source#TFSF",0x1);
		td.set("opt_numdisp_modification#Source#TFSF",0x0);
		td.set("exp_numdisp_freq#Source#TFSF","freq.val");
		td.set("flg_enable_decoupled_plane#Source#TFSF",0x0);
		td.set("opt_decoupled_plane_id#Source#TFSF",0x0);
		td.set("exp_decoupled_plane_position#Source#TFSF","0.0");
		td.set("flg_dummy_mode#Source#TFSF",0x0);
		td.set("opt_param_type#Source#FarParam",0x0);
		td.set("opt_kdir_mode#Source#FarParam",0x1);
		td.set("opt_SCS_mode#Source#FarParam",0x0);
		td.set("exp_ff.theta#Source#FarParam","plw_theta");
		td.set("exp_ff.phi#Source#FarParam","plw_phi");
		td.set("exp_ff.polar#Source#FarParam","plw_alpha");
		td.set("x3e_ff.kvec.x#Source#FarParam","-1");
		td.set("x3e_ff.kvec.y#Source#FarParam","0");
		td.set("x3e_ff.kvec.z#Source#FarParam","0");
		td.set("x3e_ff.polarvec.x#Source#FarParam","0");
		td.set("x3e_ff.polarvec.y#Source#FarParam","0");
		td.set("x3e_ff.polarvec.z#Source#FarParam","1");
		td.set("sym_lcs#Source#FarParam","#local");
	td.end();

    // 设置信号
	td.beg("signal_default","DFunctionTimeDoubleExp");
		td.set("unit","");
		td.set("exp_t_total#TimeFunc#DoubleExp","inf");
		td.set("exp_t_rise#TimeFunc#DoubleExp","1.0 / (signal_alpha / UF)");
		td.set("exp_t_fall#TimeFunc#DoubleExp","1.0 / (signal_beta / UF)");
		td.set("flg_unified#TimeFunc#DoubleExp",0x0);
	td.end();

    local solid_name = [];
    for(info in model)
    {
        local name = info.name;
        solid_name.push("Solid " .. name);
        td.beg(solid_name[end], "DSymbolPtr");
            td.set("unit","");
            td.set("meshinfo","");
            td.set("material","pec");
            td.set("n_dp_level",0x0);
            td.set("flg_style#decorator",0x0);
            td.set("exp_extra#decorator","");
            td.set("opt_extra_mode#decorator",0x0);
            td.set("sym_extra_function#decorator","");
            td.set("sym_extra_npDistrib#decorator","");
            td.set("flg_npDistrib_show#decorator",0x0);
            td.set("transforms",[]);
            td.set("reference", name);
            td.set("children", [name]);
        td.end();

        local file = fs.map2local(info.file);

        td.beg(name,"DShapeStl");
            td.set("unit","");
            td.set("fln_cadfile#Shape#Stl", file);
            td.set("flg_block#Shape#Stl", 0x0);
        td.end();

        td.beg("topgroup1");
            td.add("children", solid_name[end]);
        td.end();
    }

	td.beg("unit","DUnit");
		td.set("ul.type",0x0);
		td.set("ul.expr",unit.ul);
		td.set("ut.type",0x0);
		td.set("ut.expr",unit.ut);
		td.set("uf.type",0x0);
		td.set("uf.expr",unit.uf);
		td.set("flags",0x0);
	td.end();


	td.beg("default","DTemplateTD");
		td.set("variable#DTemplate","vartable");
		td.set("dispatcher#DTemplate","postprocess");
		td.set("FDTD.parameter#DTemplate","config");
		td.set("FDTD.topgroup#DTemplate","topgroup1");
		td.set("FDTD.workmode#DTemplate","EMP");
		td.set("FDTD.meshsetting#DTemplate","meshsetting");
	td.end();


    // 添加材料库
    for(mat in material)
    {
        local name = mat.name;
        if(mat.type == "pec")
        {
            td.beg(name,"DMaterialSimple");
                td.set("unit","");
                td.set("clr_material.color#Material#Material","#70707050");
                td.set("flg_material.extra#Material#Material",0x0);
                td.set("sym_temperatue#Material#Material","");
                td.set("exp_eps#Simple#Material","@PEC");
                td.set("exp_sge#Simple#Material","0");
                td.set("exp_xmu#Simple#Material","1");
                td.set("exp_sgm#Simple#Material","0");
            td.end();
        }

        if(mat.type == "simple")
        {
            td.beg(name,"DMaterialSimple");
                td.set("unit","#ddoc.unit.SI //国际单位制(m, s, Hz)");
                td.set("clr_material.color#Material#Material","#55D35CFF");
                td.set("flg_material.extra#Material#Material",0x0);
                td.set("sym_temperatue#Material#Material","");
                td.set("exp_eps#Simple#Material",mat.epsilon);
                td.set("exp_sge#Simple#Material",mat.sigma_e);
                td.set("exp_xmu#Simple#Material",mat.mu);
                td.set("exp_sgm#Simple#Material",mat.sigma_m);
            td.end();
        }

		if(mat.type == "lossy")
		{
			td.beg(name,"DMaterialTangent");
				td.set("unit","#ddoc.unit.emwave //微波工程常用单位(mm, ns, GHz)");
				td.set("clr_material.color#Material#Material","#EFBF97FF");
				td.set("flg_material.extra#Material#Material",0x0);
				td.set("sym_temperatue#Material#Material","");
				td.set("exp_eps#Tangent#Material","3");
				td.set("exp_tane#Tangent#Material","0.01");
				td.set("exp_freqe#Tangent#Material","1.0");
				td.set("exp_xmu#Tangent#Material","1");
				td.set("exp_tanm#Tangent#Material","0");
				td.set("exp_freqm#Tangent#Material","1.0");
			td.end();
		}
    }

    // 添加监视器
    local probe = input.probe;

    for(p in probe)
    {
		if (p.inputtype=="file"|| (!is_array(p.mtype) && p.mtype==1))
		{
			td.beg(p.name,"DMonitorTPoint");
            td.set("unit","");
            td.set("when.mode#MonitorT",0x0);
            td.set("when.s_begin#MonitorT","0");
            td.set("when.s_end#MonitorT","-1");
            td.set("when.s_delta_time#MonitorT","1.0");
            td.set("when.s_freq_width#MonitorT","freq.max * 4");
            td.set("when.s_time_series#MonitorT","0.0");
            td.set("when.t_begin#MonitorT",0x0);
            td.set("when.t_end#MonitorT",0xFFFFFFFFFFFFFFFF);
            td.set("when.t_step#MonitorT",0xFFFFFFFFFFFFFFFF);
            td.set("pos.x","0.0");
            td.set("pos.y","0.0");
            td.set("pos.z","0.0");
            td.set("opt_expand_cbox_policy#TPoint#Monitor",0x0);
            td.set("flg_custom_convergence#TPoint#Monitor",0x0);
            td.set("exp_convergence#TPoint#Monitor","30");
			if(numel(p.fieldtype)==2)
			{
				td.set("field",p.fieldtype); //注意Ex，Ey，Ez 
				td.set("field_local",0x0);
			}else
			{
				td.set("field",p.fieldtype[0].."x"); //默认记录Ex/Hx，开启局部
				td.set("field_local",0x1);
			}
        	td.end();
			td.beg(p.name .. " Group","DArrayFree");
				td.set("unit","");
				td.set("meshinfo","");
				td.set("material","");
				td.set("n_dp_level",0x0);
				td.set("flg_style#decorator",0x0);
				td.set("exp_extra#decorator","");
				td.set("opt_extra_mode#decorator",0x0);
				td.set("sym_extra_function#decorator","");
				td.set("sym_extra_npDistrib#decorator","");
				td.set("flg_npDistrib_show#decorator",0x0);
				td.set("sym_unitsymbol#Array",p.name);
				if(p.inputtype == "file")
				{
					local file = p.file;
					td.set("opt_type#Array#Free", 1);
					td.set("fln_filename#Array#Free", file);
				}else if(p.inputtype == "data")
				{
					// 输入坐标数据
					local data = p.data;
					td.set("opt_type#Array#Free", 0);
					local data_in = [];
					if(p.flag=="point_array")
					{
							for(local i=0; i<numel(data); i+=3)
							{
								data_in.push([data[i], data[i+1], data[i+2]]);
							}
					}
					else if(p.flag=="point_list")
					{	
						local name_info=[]				
						for(local i=0; i<numel(data); i++)
						{
							data_in.push([data[i][1], data[i][2], data[i][3]]);
							name_info.push(data[i][0]);
						}
						local t_path=fs.filename(input_file).path;
						local fn=t_path.."/"..p.name.."_Pointlist.csv";
						io.save_csv(fn,name_info);  //保存点名
					}
					td.set("mvm_point3s#Array#Free",data_in);
				}
				else
				{
					logger.log_message(format("probe type：%{1} unsupport",p.inputtype))
				}
			td.end();

			td.beg("topgroup1");
				td.add("children", p.name .. " Group");
			td.end();
		}
		else if(p.inputtype=="data" && is_array(p.mtype))
		{
			//local groupset=[];
			local groupset=[];
			local name_2d=[];//面
			local name_3d=[];//体
			local name_4d=[];//远场
			local dir_table =table{
						xoy:2;
						yoz:0;
						zox:1;
						volume:3
					};
			local field_table=table{
							Ex:	0x1;
							Ey:	0x2;
							Ez: 0x4;
							EVec: 0x7;
							Hx: 0x8;
							Hy: 0x10;
							Hz: 0x20;
							HVec: 0x38;
							`EVec&HVec`:0x3F
					};
			for(local jj=0;jj<numel(p.mtype);jj++)
			{
				local type_info = p.flag[jj];
				local p_name = p.name; //父类名
				local c_name = p.data[jj][0]; //具体内层名
				local m_flag = p.flag[jj]; //["xoy","yoz","zox","volume"]
			
				local dir_index = dir_table[m_flag];
				local  val = p.mtype[jj];
				//logger.log_message(format("Probe %{1}——%{2}Type:%{3}——%{4}",p_name,c_name,m_flag,val))
				switch(val)
				{
					
					case 2:{ //面
								//name p.Name
								if(p.type=="FREQ_DOMAIN")
								{
									td.beg(c_name,"DMonitorFSliceCpx");
									td.set("unit","");
									td.set("freq",math.var2exp(p.freq));
									td.set("when.mode#MonitorF",0x0);
									td.set("when.s_begin#MonitorF","0");
									td.set("when.s_end#MonitorF","-1");
									td.set("when.s_delta_time#MonitorF","1.0");
									td.set("when.s_freq_width#MonitorF","freq.max * 4");
									td.set("when.s_time_series#MonitorF","0.0");
									td.set("when.t_begin#MonitorF",0x0);
									td.set("when.t_end#MonitorF",0xFFFFFFFFFFFFFFFF);
									td.set("when.t_step#MonitorF",0x1);
									td.set("x3e_box_lo.x#Box2D#FSliceCpx#Monitor",p.data[jj][1]);
									td.set("x3e_box_lo.y#Box2D#FSliceCpx#Monitor",p.data[jj][2]);
									td.set("x3e_box_lo.z#Box2D#FSliceCpx#Monitor",p.data[jj][3]);
									td.set("x3e_box_hi.x#Box2D#FSliceCpx#Monitor",p.data[jj][4]);
									td.set("x3e_box_hi.y#Box2D#FSliceCpx#Monitor",p.data[jj][5]);
									td.set("x3e_box_hi.z#Box2D#FSliceCpx#Monitor",p.data[jj][6]);
									td.set("opt_mode#Box2D#FSliceCpx#Monitor",0x0+dir_index);
									td.set("opt_policy_offset#Box2D#FSliceCpx#Monitor",0x0);
									td.set("field",p.fieldtype);
									td.set("field_local",0x0);
									td.set("opt_direction#FSliceCpx#Monitor",0x0);
									td.set("opt_expand_cbox_policy#Box2D#FSliceCpx#Monitor",0x1);
									td.set("opt_broadband_mode#FSliceCpx#Monitor",0x0);
									td.set("exp_broadband_fmin#FSliceCpx#Monitor","freq.min");
									td.set("exp_broadband_fmax#FSliceCpx#Monitor","freq.max");
									td.set("exp_broadband_forder#FSliceCpx#Monitor","20");
									td.end();
								}else
								{
									td.beg(c_name,"DMonitorTSliceRaw");
									td.set("unit","");
									td.set("when.mode#MonitorT",0x0);
									td.set("when.s_begin#MonitorT","0");
									td.set("when.s_end#MonitorT","-1");
									td.set("when.s_delta_time#MonitorT","1.0");
									td.set("when.s_freq_width#MonitorT","freq.max * 4");
									td.set("when.s_time_series#MonitorT","0.0");
									td.set("when.t_begin#MonitorT",0x0);
									td.set("when.t_end#MonitorT",0xFFFFFFFFFFFFFFFF);
									td.set("when.t_step#MonitorT",0xFFFFFFFFFFFFFFFF);
									td.set("shape","");
									td.set("x3e_box_lo.x#Box2D#TSliceRaw#Monitor",p.data[jj][1]);
									td.set("x3e_box_lo.y#Box2D#TSliceRaw#Monitor",p.data[jj][2]);
									td.set("x3e_box_lo.z#Box2D#TSliceRaw#Monitor",p.data[jj][3]);
									td.set("x3e_box_hi.x#Box2D#TSliceRaw#Monitor",p.data[jj][4]);
									td.set("x3e_box_hi.y#Box2D#TSliceRaw#Monitor",p.data[jj][5]);
									td.set("x3e_box_hi.z#Box2D#TSliceRaw#Monitor",p.data[jj][6]);
									td.set("opt_mode#Box2D#TSliceRaw#Monitor",0x0+dir_index);  //YOZ自动->0x3E8，ZOX自动->0x3E9,XOY自动->0x3EA,YOZ->0x0，ZOX->0x1,XOY->0x2
									td.set("opt_policy_offset#Box2D#TSliceRaw#Monitor",0x0);
									td.set("field",p.fieldtype);
									td.set("field_local",0x0);
									td.set("opt_expand_cbox_policy#Box2D#TSliceRaw#Monitor",0x1);
									td.set("opt_direction#TSliceRaw#Monitor",0x0);
									td.end();
								}
								name_2d.push(c_name);
								groupset.push(c_name);
							};
					case 3:{ //体
											
							local field_index=field_table[p.fieldtype];
							if(p.type=="FREQ_DOMAIN")
							{
								td.beg(c_name,"DMonitorF_Volume");
								td.set("unit","");
								td.set("freq","linspace(freq.min, freq.max, 11)");
								td.set("when.mode#MonitorF",0x0);
								td.set("when.s_begin#MonitorF","0");
								td.set("when.s_end#MonitorF","-1");
								td.set("when.s_delta_time#MonitorF","1.0");
								td.set("when.s_freq_width#MonitorF","freq.max * 4");
								td.set("when.s_time_series#MonitorF","0.0");
								td.set("when.t_begin#MonitorF",0x0);
								td.set("when.t_end#MonitorF",0xFFFFFFFFFFFFFFFF);
								td.set("when.t_step#MonitorF",0x1);
								td.set("x3e_box.lo.x#DMonitorF_Volume",p.data[jj][1]);
								td.set("x3e_box.lo.y#DMonitorF_Volume",p.data[jj][2]);
								td.set("x3e_box.lo.z#DMonitorF_Volume",p.data[jj][3]);
								td.set("x3e_box.hi.x#DMonitorF_Volume",p.data[jj][4]);
								td.set("x3e_box.hi.y#DMonitorF_Volume",p.data[jj][5]);
								td.set("x3e_box.hi.z#DMonitorF_Volume",p.data[jj][6]);
								td.set("delta#DMonitorF_Volume","10");
								td.set("freqs#DMonitorF_Volume",math.var2exp(p.freq));
								td.set("flg_field#DMonitorF_Volume",field_index);
								td.end();
							}else
							{
								td.beg(c_name,"DMonitorT_Volume");
								td.set("unit","");
								td.set("when.mode#MonitorT",0x0);
								td.set("when.s_begin#MonitorT","0");
								td.set("when.s_end#MonitorT","-1");
								td.set("when.s_delta_time#MonitorT","1.0");
								td.set("when.s_freq_width#MonitorT","freq.max * 4");
								td.set("when.s_time_series#MonitorT","0.0");
								td.set("when.t_begin#MonitorT",0x0);
								td.set("when.t_end#MonitorT",0xFFFFFFFFFFFFFFFF);
								td.set("when.t_step#MonitorT",0xFFFFFFFFFFFFFFFF);
								td.set("x3e_box.lo.x#DMonitorT_Volume",p.data[jj][1]);
								td.set("x3e_box.lo.y#DMonitorT_Volume",p.data[jj][2]);
								td.set("x3e_box.lo.z#DMonitorT_Volume",p.data[jj][3]);
								td.set("x3e_box.hi.x#DMonitorT_Volume",p.data[jj][4]);
								td.set("x3e_box.hi.y#DMonitorT_Volume",p.data[jj][5]);
								td.set("x3e_box.hi.z#DMonitorT_Volume",p.data[jj][6]);
								td.set("delta#DMonitorT_Volume","10");
								td.set("flg_field#DMonitorT_Volume",field_index);
								td.end();
							};
							name_3d.push(c_name);
							groupset.push(c_name);
							
							};
					case 4:{
						//will do 远场/球
						print("will do");
							};
					default:{
							print("other value");
							};

				};
				
			}
			/*if(numel(name_2d)>0)
			{
				local path=fs.filename(input_file).path;
				local fn=path.."/"..p.name.."_Region.csv";
				logger.log_message(format("Save file:%{1}",fn));
				io.save_csv(fn,name_2d);  //保存区域场名	
			}
			if(numel(name_3d)>0)
			{
				local path=fs.filename(input_file).path;
				local fn=path.."/"..p.name.."_Volume.csv";
				logger.log_message(format("Save file:%{1}",fn));
				io.save_csv(fn,name_3d);  //保存体记录名	
			}
			if(numel(name_4d)>0)
			{
				local path=fs.filename(input_file).path;
				local fn=path.."/"..p.name.."_Far.csv";
				logger.log_message(format("Save file:%{1}",fn));
				io.save_csv(fn,name_4d);  //保存远场名
			}*/
				
			if(numel(groupset)>0)			
			{	
				td.beg(p.name.."_MonitorGroup","DSymbolGrp");
					td.set("unit","");
					td.set("meshinfo","");
					td.set("material","");
					td.set("n_dp_level",0x0);
					td.set("flg_style#decorator",0x0);
					td.set("exp_extra#decorator","");
					td.set("opt_extra_mode#decorator",0x0);
					td.set("sym_extra_function#decorator","");
					td.set("sym_extra_npDistrib#decorator","");
					td.set("flg_npDistrib_show#decorator",0x0);
					td.set("transforms",[]);
					td.set("children",groupset);
					td.set("reference",groupset[0]);
				td.end();
				td.beg("topgroup1");
				td.add("children", p.name.."_MonitorGroup");
				td.end();
			} 
		}
		else
		{
			logger.log_message("This Type %s -->%s",p.inputtype,p.mtype);
		}
			
    }


    // 设置线缆
	for(ind, v in cable)
	{
		local cable_data = io.readfile(v.file);
		// 线缆截面
		td.beg("cable_cs" .. ind,"DCableWireSingle");
			td.set("exp_thickness#Conductor#WireSingle",v.core_radius);
			td.set("material#Conductor#WireSingle",v.core_mat);
			td.set("exp_thickness#Insulator#WireSingle",v.coat_thick);
			td.set("material#Insulator#WireSingle",v.coat_mat);
		td.end();
		// 线缆连接
		td.beg("cable_link" .. ind,"DCableWireSingleWithBase");
		//td.beg(cable.name,cable.style)
			td.set("exp_distance_ground#WireSingleWithBase",v.gnd_distance);
			td.set("wire_single#WireSingleWithBase","cable_cs"..ind); 
		td.end();



		// 线缆束
		td.beg("cable" .. ind,"DCableBundle");
			td.set("unit","");
			td.set("type#Segs#CableBundle",0x2);
			td.set("flags#Segs#CableBundle",0x3);
			/*
			td.set("mvm_point3s#Segs#CableBundle",[]);
			td.set("x3e_pos_beg.x#Segs#CableBundle","-6500");
			td.set("x3e_pos_beg.y#Segs#CableBundle","0");
			td.set("x3e_pos_beg.z#Segs#CableBundle","0");
			td.set("x3e_pos_end.x#Segs#CableBundle","6500");
			td.set("x3e_pos_end.y#Segs#CableBundle","0");
			td.set("x3e_pos_end.z#Segs#CableBundle","0");
			td.set("x3e_pos_mid.x#Segs#CableBundle","0");
			td.set("x3e_pos_mid.y#Segs#CableBundle","0");
			td.set("x3e_pos_mid.z#Segs#CableBundle","0");
			*/
			td.set("s_n#Segs#CableBundle",cable_data);
			td.set("s_t#Segs#CableBundle","[-1,1]");
			td.set("s_x#Segs#CableBundle","0");
			td.set("s_y#Segs#CableBundle","0");
			td.set("s_z#Segs#CableBundle","_t");
			td.set("cable_wires",["cable_link" .. ind]);
			td.set("Cables#CableBundle","");
			td.set("tb_cable_port#CableBundle",[]);
			td.set("freqs#CableBundle","freq.data");  // 线缆记录的频率
			td.set("cable_segment#CableBundle","10");
			td.set("flg_force_snap#CableBundle",0x1);
			td.set("type#wire#CableBundle",0x0);
			td.set("exp_distance_ground#CableBundle","10");
			td.set("RLCG_algorithm#CableBundle",0x0);
			td.set("type#mesh#CableBundle",0x1);
			td.set("mesh_min_ratio#CableBundle","0.5");
			td.set("mesh_max_ratio#CableBundle","100");
			td.set("ref_freq_ratio#CableBundle","freq.max");
			td.set("mesh_min_val#CableBundle","0.1");
			td.set("mesh_max_val#CableBundle","1.0");
			td.set("opt_unit_length#mesh#CableBundle",0x2);
		td.end();

        td.beg("topgroup1");
            td.add("children", "cable" .. ind);
        td.end();
	};


	//添加集总端口
	for(k,v in param2.PORT_IN)
	{
		if(v.port_type == "DLumpedPort")
		{
			td.beg(v.port_name,"DLumpedPort");
					td.set("unit","");
					td.set("flg_update_as_shape#Source",0x1);
					td.set("sym_signal#LumpedPort","signal_default");
					td.set("exp_intensity#LumpedPort","0");
					td.set("exp_delay#LumpedPort","0.0");
					td.set("exp_phase#LumpedPort","0.0");
					td.set("opt_define#LumpedPort",0x1);
					td.set("exp_radius#LumpedPort","0.01");
					td.set("x3e_line_st_point.x#LumpedPort", v.port_params.start_x);
					td.set("x3e_line_st_point.y#LumpedPort", v.port_params.start_y);
					td.set("x3e_line_st_point.z#LumpedPort", v.port_params.start_z);
					td.set("x3e_line_ed_point.x#LumpedPort",v.port_params.end_x);
					td.set("x3e_line_ed_point.y#LumpedPort",v.port_params.end_y);
					td.set("x3e_line_ed_point.z#LumpedPort",v.port_params.end_z);
					td.set("x3e_position.x#LumpedPort","0.0");
					td.set("x3e_position.y#LumpedPort","0.0");
					td.set("x3e_position.z#LumpedPort","0.0");
					td.set("opt_direction#LumpedPort",0x2);
					td.set("flg_reverse#LumpedPort",0x0);
					td.set("flg_force_snap#LumpedPort",0x0);
					td.set("sym_material#LumpedPort","#ddoc.material.vacuum");
					td.set("path#LumpedPort","");
					td.set("exp_R#LumpedPort",v.port_params.exp_R_LumpedPort);
					td.set("exp_C#LumpedPort","0.0");
					td.set("exp_L#LumpedPort","0.0");
					td.set("opt_circuit_type#LumpedPort",0x0);
					td.set("opt_feedtype#LumpedPort",0x1);
					td.set("delta_c#NONLINEAR_C#LumpedPort","0.0");
					td.set("alpha#NONLINEAR_C#LumpedPort","0.0");
					td.set("chi3#NONLINEAR_C#LumpedPort","0.0");
					td.set("chi2#NONLINEAR_C#LumpedPort","0.0");
					td.set("delta_freq#NONLINEAR_C#LumpedPort","1.0");
					td.set("raman_freq#NONLINEAR_C#LumpedPort","1.0");
					td.set("R#Diode#LumpedPort","0.0");
					td.set("C#Diode#LumpedPort","0.0");
					td.set("Gs#Diode#LumpedPort","0.0");
					td.set("I0#Diode#LumpedPort","1e-14");
					td.set("Temperature#Diode#LumpedPort","300");
					td.set("flg_Gs_active#Diode#LumpedPort",0x0);
					td.set("flg_calSparam#LumpedPort",0x1);
					td.set("flg_monitorVandI#LumpedPort",0x1);
					td.set("flg_custom_convergence#LumpedPort",0x0);
					td.set("exp_convergence#LumpedPort","30");
				td.end();
				td.beg("topgroup1");
					td.add("children", v.port_name);
				td.end();			
		}
		else
		{
			throw "invalid port";
		}
	}



	td.beg("postprocess","DDispatcherOnce");
		td.set("unit","");
		td.set("post_type",0x1);
		td.set("extra_script","");
		//E:\ew_project\ew_bin\ew7\scripting\library\monitor_postp
		td.set("extra_script_file","app:/scripting/library/monitor_postp/monitor_preload.mx");
	td.end();
	/*
		if(!is_nil(output))
		{
			// 保存到指定的文件名
			td.save(output);
		}
	*/

	local input_file_nfo = fs.filename(input_file);

	local project_file = input_file_nfo.path .. "/" .. input_file_nfo.name .. ".ewp2";
	logger.log_message("SAVE Project File: %s", project_file);
    
	td.save(project_file);
    //fs.exists(input.output.path)
	local target_folder=input.output.fpath;
	switch(fs.exists(target_folder))
    {
    case 0:
        // 不存在，创建文件夹
        fs.mkdir(target_folder);
        logger.log_message("Create folder: %s", target_folder);
    case 1:
        // 错误是个文件
        logger.log_error("Cannot create folder: %s", target_folder);
        break;
    case 2:
    }
	io.save_var(param_file,input);
	td.run(0);

td.end();



